$(function () {
  $('.dropify').dropify({
    messages: {
      'default': '点击或拖拽文件到这里',
      'replace': '点击或拖拽文件到这里来替换文件',
      'remove': '移除文件',
      'error': '对不起，你上传的文件太大了',
    }
  });

  var options = {
    aspectRatio: 1,
    rotatable: false,
    viewMode: 2,
    preview: '.img-preview'

  };

  var $inputImage = $('#inputFileNow');
  var $image = $('#img1');

  var originalImageURL = $image.attr('src');
  var uploadedImageName = 'cropped.jpg';
  var uploadedImageType = 'image/jpeg';
  var uploadedImageURL;

  $image.cropper(options);
  var cropper = $image.data('cropper');

  var URL = window.URL || window.webkitURL;

  if (URL) {
    $inputImage.change(function () {
      var files = this.files;
      var file;

      if (!$image.data('cropper')) {
        return;
      }

      if (files && files.length) {
        file = files[0];
        if (/^image\/\w+$/.test(file.type)) {
          uploadedImageName = file.name;
          uploadedImageType = file.type;

          if (uploadedImageURL) {
            URL.revokeObjectURL(uploadedImageURL);
          }

          uploadedImageURL = URL.createObjectURL(file);
          $image.cropper('destroy').attr('src', uploadedImageURL).cropper(options);
          //$inputImage.val('');
        } else {
          window.alert('未知的图片格式');
        }
      }
    });
  } else {
    $inputImage.prop('disabled', true).parent().addClass('disabled');
  }

});

function btn_get() {
  var $image = $('#img1');
  var data = $image.cropper('getData');
  return data;
}

function submitForm(index) {
  var files=$('#inputFileNow')[0].files;
  if(files.length<=0){
    top.$.modalAlert('未选择文件');
  }

  top.$.loadingBox(false);

  var formData = new FormData($("#form1")[0]);

  var cropData=btn_get();
  var str='';
  for(var k in cropData){
    str+='&'+k+'='+Math.round(cropData[k]);
  }

  $.ajax({
    url: "/SystemManage/User/CustomAvatarSubmit?id=" + $.request('id')+str,
    data: formData,
    type: 'POST',
    async: true,
    cache: false,
    processData: false,
    contentType: false,
    beforeSend: function (xhr) {
      xhr.setRequestHeader("XSRF-TOKEN",
          $('[name="__RequestVerificationToken"]').val());
    },
    success: function (returndata) {
      top.$.loadingBox(true);
      if(returndata.state=='success'){
        top.frames['layui-layer-iframe' + index].location.reload();
        $.modalClose();
      }
      else{
        $.modalAlert(retundata.message);
      }
    },
    error: function (returndata) {
      top.$.loadingBox(true);
      $.modalAlert(retundata.message);

    }
  });


};